"""
配置管理模块
"""
import os
from dataclasses import dataclass
from typing import Optional


@dataclass
class AIModelConfig:
    """AI模型配置"""
    api_base: str
    api_key: str
    model: str
    max_tokens: int = 4000
    temperature: float = 0.7
    timeout: int = 60
    max_retries: int = 3
    
    @classmethod
    def from_env(cls) -> 'AIModelConfig':
        """从环境变量创建配置"""
        return cls(
            api_base=os.getenv('OPENAI_API_BASE', 'https://api.openai.com/v1'),
            api_key=os.getenv('OPENAI_API_KEY', ''),
            model=os.getenv('OPENAI_MODEL', 'gpt-3.5-turbo'),
            max_tokens=int(os.getenv('OPENAI_MAX_TOKENS', '4000')),
            temperature=float(os.getenv('OPENAI_TEMPERATURE', '0.7')),
            timeout=int(os.getenv('OPENAI_TIMEOUT', '60')),
            max_retries=int(os.getenv('OPENAI_MAX_RETRIES', '3'))
        )


@dataclass
class AppConfig:
    """应用配置"""
    flask_env: str
    secret_key: str
    log_level: str
    max_execution_time: int
    host: str = '0.0.0.0'
    port: int = 5000
    debug: bool = False
    
    @classmethod
    def from_env(cls) -> 'AppConfig':
        """从环境变量创建配置"""
        flask_env = os.getenv('FLASK_ENV', 'production')
        return cls(
            flask_env=flask_env,
            secret_key=os.getenv('SECRET_KEY', 'your-secret-key-here'),
            log_level=os.getenv('LOG_LEVEL', 'INFO'),
            max_execution_time=int(os.getenv('MAX_EXECUTION_TIME', '300')),
            host=os.getenv('HOST', '0.0.0.0'),
            port=int(os.getenv('PORT', '5000')),
            debug=flask_env == 'development'
        )


class Config:
    """统一配置管理"""
    
    def __init__(self):
        self.ai_model = AIModelConfig.from_env()
        self.app = AppConfig.from_env()
    
    def validate(self) -> bool:
        """验证配置有效性"""
        if not self.ai_model.api_key:
            raise ValueError("OPENAI_API_KEY is required")
        
        if not self.ai_model.api_base:
            raise ValueError("OPENAI_API_BASE is required")
        
        if not self.ai_model.model:
            raise ValueError("OPENAI_MODEL is required")
        
        return True


# 全局配置实例
config = Config()